from PIL import Image
import os

def resize_images_to_width_or_height(folder_path, target_width=None, target_height=None):
    """
    将文件夹内所有图片等比例缩放到指定宽度或高度。

    :param folder_path: 文件夹路径
    :param target_width: 指定目标宽度（像素），可以为 None
    :param target_height: 指定目标高度（像素），可以为 None
    """
    if target_width is None and target_height is None:
        raise ValueError("必须至少指定 target_width 或 target_height")
    
    try:
        for root, _, files in os.walk(folder_path):
            for filename in files:
                if filename.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp', '.gif', '.tiff')):
                    file_path = os.path.join(root, filename)
                    
                    # 打开图片
                    with Image.open(file_path) as img:
                        # 获取原始尺寸
                        original_width, original_height = img.size
                        
                        # 根据指定的目标宽度或高度计算缩放比例
                        if target_width is None:  # 仅指定目标高度
                            scale_ratio = target_height / original_height
                            new_width = int(original_width * scale_ratio)
                            new_height = target_height
                            print("--",target_height,original_height)

                        elif target_height is None:  # 仅指定目标宽度
                            scale_ratio = target_width / original_width
                            new_width = target_width
                            new_height = int(original_height * scale_ratio)
                        else:  # 同时指定目标宽度和高度，选择较小的缩放比例
                            width_ratio = target_width / original_width
                            height_ratio = target_height / original_height
                            scale_ratio = min(width_ratio, height_ratio)
                            new_width = int(original_width * scale_ratio)
                            new_height = int(original_height * scale_ratio)
                        
                        # 如果需要缩放
                        if scale_ratio > 1:
                            resized_img = img.resize((new_width, new_height), Image.Resampling.LANCZOS)
                            
                            # 保存修改后的图片
                            resized_img.save(file_path)
                            print(f"Resized: {file_path} from ({original_width}, {original_height}) to ({new_width}, {new_height})")
                        else:
                            print(f"Skipped (no resize needed): {file_path}")
    except Exception as e:
        print(f"Error: {e}")
        
#图片重新设置尺寸
# 示例用法----
folder_path = r"D:\dage\david_共享\设计图\财富"  # 替换为目标文件夹路径
target_width = None                 # 设置目标宽度（像素），可设为 None
target_height = 1080                # 设置目标高度（像素），可设为 None

resize_images_to_width_or_height(folder_path, target_width=target_width, target_height=target_height)
